package com.bbms.dao.impl;

import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.bbms.dao.LogoutBookReportDAO;
import com.bbms.entity.Book;
import com.bbms.entity.Page;
import com.bbms.util.HibernateUtil;
import com.bbms.util.StringUtil;

@Repository("LogoutBookReportDAOImpl")
public class LogoutBookReportDAOImpl implements LogoutBookReportDAO {

	@Override
	public void save(Book t) {

	}

	@Override
	public void update(Book t) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(Book t) {
		// TODO Auto-generated method stub

	}

	@Override
	public Page getPage(int currentPage, int pageSize) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<?> query() {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Page getPage(int currentPage, int pageSize, String start_time, String end_time) {

		StringBuffer sb = new StringBuffer();
		StringBuffer total = new StringBuffer();
		sb.append("SELECT b.`name`, b.publish_date AS publishDate, b.ISBN, COUNT(b.id) AS num "
				+ "FROM bbms_book AS b "
				+ "WHERE b.`status` = -1 ");
		
		total.append("SELECT COUNT(t.total) AS total "
				+ "FROM (SELECT COUNT(publish_date) AS total "
				+ "FROM bbms_book AS b "
				+ "WHERE b.`status` = -1 ");
		
		if (!StringUtil.isEmpty(start_time)){
			sb.append("AND UNIX_TIMESTAMP(b.book_logout_time) >= UNIX_TIMESTAMP('" + start_time + "') ");
			total.append("AND UNIX_TIMESTAMP(b.book_logout_time) >= UNIX_TIMESTAMP('" + start_time + "') ");
		}
		if (!StringUtil.isEmpty(end_time)){
			sb.append("AND UNIX_TIMESTAMP(b.book_logout_time) <= UNIX_TIMESTAMP('" + end_time + "') ");
			total.append("AND UNIX_TIMESTAMP(b.book_logout_time) <= UNIX_TIMESTAMP('" + end_time + "') ");
		}
		
		sb.append("GROUP BY b.`name`, b.ISBN ");
		sb.append("LIMIT " + ((currentPage - 1)* pageSize) + "," + pageSize);
		total.append("GROUP BY b.`name`, b.ISBN ) AS t");
		Page page = new Page();
		System.out.println(sb.toString());
		List<?> list = HibernateUtil.executeSqlQuery(sb.toString());
		page.setPageNo(currentPage);
		page.setPageSize(pageSize);
		page.setRows(list);
		System.out.println(total.toString());
		List<HashMap> l = (List<HashMap>) HibernateUtil.executeSqlQuery(total.toString());
		
		page.setTotal(Integer.parseInt(l.get(0).get("total").toString()));
		
		return page;
	}

}
